package com.wzk.travelspringboot.common;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/5 12:34
 */
@Slf4j
public class LogToFile {

    private static final ExecutorService threadPool = new ThreadPoolExecutor(
            1,
            1,
            0l,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(2000),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //把data存到名为name的log文件夹里，要传入当前类的logger
    public static void logToFile(String data, Logger logger, String name) {
        //日志异步写入
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                    String logFileName = "logs/"+name+"/"+name + currentDate + ".log";
                    Path logFilePath = Paths.get(logFileName);
                    // 创建目录，如果目录不存在
                    Files.createDirectories(logFilePath.getParent());
                    // 如果文件不存在，创建新文件；如果文件已存在，以追加方式打开
                    Files.write(logFilePath, formatLogMessage(data).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
                } catch (IOException e) {
                    log.error("日志写入失败出现：{}",e.getMessage());
                }
            }
        });
    }
    // 将日志数据格式化
    private static String formatLogMessage(String message) {
        return "[" + dateFormat.format(new Date()) + "] " + message + System.lineSeparator();
    }

}
